import { listDictionaryData } from '@/api/system/dictionary-data'
import { useUserStore } from '@/store/modules/user'
import { EleMessage } from 'ele-admin-plus'

/**
 * 获取字典数据hook
 * @param codes 字典编码
 */
export function useDictData(codes) {
  const result = []

  // 已缓存的字典
  const userStore = useUserStore()
  const { dicts } = storeToRefs(userStore)

  codes.forEach((code) => {
    result.push(computed(() => dicts.value[code] || []))
    // 若还未缓存过则获取字典数据
    if (dicts.value[code] != null) {
      return
    }
    userStore.setDicts([], code)
    listDictionaryData({ dictCode: code })
      .then((list) => {
        userStore.setDicts(list, code)
      })
      .catch((e) => {
        EleMessage.error({ message: e.message, plain: true })
      })
  })

  return result
}
